package edu.gdin.ecommerce.security.support;

import java.util.ArrayList;
import java.util.Collection;

import javax.annotation.Resource;

import org.springframework.dao.DataAccessException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;

import edu.gdin.ecommerce.dao.RoleDAO;
import edu.gdin.ecommerce.dao.UserDAO;

public class MyUserDetailsService implements UserDetailsService  {
	
	private UserDAO userDAO;
	private RoleDAO roleDAO;
	 	
	public UserDAO getUserDAO() {
		return userDAO;
	}

	@Resource
	public void setUserDAO(UserDAO userDAO) {
		this.userDAO = userDAO;
	}

	public RoleDAO getRoleDAO() {
		return roleDAO;
	}
	
	@Resource
	public void setRoleDAO(RoleDAO roleDAO) {
		this.roleDAO = roleDAO;
	}

	public UserDetails loadUserByUsername(String username)
			throws UsernameNotFoundException, DataAccessException {
		
		Collection<GrantedAuthority> auths = new ArrayList<GrantedAuthority>();
		//取得用户的权限
		auths=userDAO.findRoleByAccount(username);
		if(auths == null) {  
			throw new UsernameNotFoundException(username);  
	    }  
		String password = userDAO.getUserByAccount(username).getPassword();
        User user = new User(username, password, true, true, true, true, auths);
        System.out.println("登陆用户信息:" + username + auths);
        
        return user;
	}

}
